/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.chl.cid.beans;

import edu.chl.cid.entities.Product;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

/**
 *
 * @author rhodinj
 */
@ManagedBean
//@RequestScoped
@SessionScoped
public class ShoppingCart {
    private List<Item> products;

    public ShoppingCart() {
        products = new ArrayList<Item> ();
    }

    public List<Item> getProducts() {
        return products;
    }

    public void setProducts(List<Item> products) {
        this.products = products;
    }

    public void addItem(Item i)
    {
        for (Item j : products)
        {
            if (j.getId().equals(i.getId()))
            {
                j.setQuantity(j.getQuantity() + 1);
                return;
            }
        }

        products.add(i);
    }

    public void addProduct(Product p)
    {
        for (Item i : products)
        {
            if (i.getId().equals(p.getId()))
            {
                i.setQuantity(i.getQuantity() + 1);
                return;
            }
        }
        products.add(new Item(p.getId(), p.getName(), p.getCat(), p.getDesc(), p.getPrice(), 1));
    }

    public void removeAllItem(Item i)
    {
        products.remove(i);
    }

    public void removeOneItem(Item i)
    {
        for (Item j : products)
        {
            if (j.getId().equals(i.getId()))
            {
                j.setQuantity(j.getQuantity() - 1);
                if (j.getQuantity()==0)
                    products.remove(j);
                return;
            }
        }
    }

    public double getTotalPrice() {
        double total = 0;
        for (Item i : products)
        {
            total+=i.getPrice()*i.getQuantity();
        }
        return total;
    }

    public int getSize() {
        if (products==null)
            return 0;
        else
        {
            int size=0;
            for (Item i : products)
                size+=i.getQuantity();
            return size;
        }
    }

    public void clear(){
        products.clear();
    }
}
